package com.ywjt.platformbusiness.market.integralgoods.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.stx.xhb.xbanner.XBanner;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.market.commongoods.activity.ActivityCommentDetail;
import com.ywjt.platformbusiness.market.commongoods.adapter.GoodsDetailCommentAdapter;
import com.ywjt.platformbusiness.market.commongoods.model.GoodsDetail;
import com.ywjt.platformbusiness.market.integralgoods.model.IntegralGoodsDetailModel;
import com.ywjt.platformbusiness.util.JsonUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class IntegralGoodsDetail extends BaseActivity implements View.OnClickListener {

    private XBanner banner;
    private IntegralGoodsDetailModel goodsDetail;
    private LinearLayout llBuy;
    private LinearLayout llAddCart;
    private TextView tvHeat;
    private int goodsnumn=1;
    private String goodsid="";
    private LinearLayout llCart;
    private TextView tvGoodsName,tvPostAddress;
    private TextView tvStock;
    private TextView tvIntegral;
    private TextView tvGoodPrice;
    private WebView tvDetail;
    private LinearLayout llSpecs;
    private LinearLayout llcallservice;
    private TextView tvOldPrice;
    private TextView tvBuyNum;
    private RecyclerView rcCommon;
    private TextView tvMore;
    private GoodsDetailCommentAdapter detailCommentAdapter;

    private List<String> banners;

    public static void actionStart(Context context,String goodsid) {
        Intent intent = new Intent(context, IntegralGoodsDetail.class);
        intent.putExtra("goodsid",goodsid);
        context.startActivity(intent);
    }

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, IntegralGoodsDetail.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tvMore:
                ActivityCommentDetail.actionStart(this);
                break;
            case R.id.llBuy:
                ActivityIntegralSettleMent.actionStart(this);
                break;
        }
    }

//    //添加商品到购物车
//    public void addCart(String skuid){
//        Map<String,Object> map=new HashMap<>();
//        map.put("goodsId",String.valueOf(goodsid));//商品id
//        map.put("userId",getUserId(getContext()));//用户id
//        map.put("number",String.valueOf(goodsnumn));//数量
//        map.put("goodsSkuId",skuid);//库存id
//        new HttpRequest(getContext()).doPost(UrlConstants.goodsShopCart_addShopCard, null, map, BaseModel.class, new HttpStringCallBack() {
//            @Override
//            public void onSuccess(Object result) {
//                if (result instanceof BaseModel) {
//                   BaseModel model=(BaseModel)result;
//                   if(model.getCode()==200){
//                       ToastUtil toastUtil=new ToastUtil(getContext(),R.layout.popu_resetsuccess,"添加成功，在购物车等亲~",1);
//                       toastUtil.show();
//                   }else {
//                       ToastUtil toastUtil=new ToastUtil(getContext(),R.layout.popu_success,model.getMessage(),2);
//                       toastUtil.show();
//                   }
//                }
//            }
//
//            @Override
//            public void onFailure(int code, String msg) {
//                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
//            }
//        });
//    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_integralgoodsdetail;
    }

    @Override
    protected void initView() {
        setTitleText("商品详情");
        goodsid=getIntent().getStringExtra("goodsid");
        llBuy=findViewById(R.id.llBuy);
        rcCommon=findViewById(R.id.rcCommon);
        tvBuyNum=findViewById(R.id.tvBuyNum);
        tvPostAddress=findViewById(R.id.tvPostAddress);
        tvStock=findViewById(R.id.tvStock);
        llBuy.setOnClickListener(this::onClick);
        llAddCart=findViewById(R.id.llAddCart);
        tvGoodPrice=findViewById(R.id.tvGoodPrice);
        tvIntegral=findViewById(R.id.tvIntegral);
        tvOldPrice=findViewById(R.id.tvOldPrice);
        tvHeat=findViewById(R.id.tvHeat);
        tvGoodsName=findViewById(R.id.tvGoodName);
        llAddCart.setOnClickListener(this::onClick);
        banner=findViewById(R.id.banner);
        tvMore=findViewById(R.id.tvMore);
        tvDetail=findViewById(R.id.tvDetail);
        llCart=findViewById(R.id.llCart);
        llCart.setOnClickListener(this::onClick);
        tvMore.setOnClickListener(this::onClick);
        llcallservice=findViewById(R.id.llcallservice);
        llcallservice.setOnClickListener(this::onClick);

//        detailCommentAdapter=new GoodsDetailCommentAdapter(data);
//        rcCommon.setAdapter(detailCommentAdapter);
//        rcCommon.setLayoutManager(new LinearLayoutManager(this));

        getData();
    }

    //获取商品详情
    public void getData(){

        new HttpRequest(getContext()).doGet(UrlConstants.getCommodityIntegralDetail+goodsid,null, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    int code = jsonObject.getInt("code");
                    if (code == 200) {
                        Object obj = JsonUtils.fromJson(result.toString(), IntegralGoodsDetailModel.class);
                        if (obj instanceof IntegralGoodsDetailModel) {
                               goodsDetail = (IntegralGoodsDetailModel) obj;
                           setView();
                           setBanner();
                        }
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    //设置数据
    public void setView(){
        tvGoodsName.setText(goodsDetail.getResult().getCommodityMessage().getName());
        tvGoodPrice.setText("￥"+goodsDetail.getResult().getAmount());
        tvOldPrice.setText("￥"+goodsDetail.getResult().getPrice());
        tvOldPrice.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG );
        tvIntegral.setText("+"+goodsDetail.getResult().getIntegral()+"积分");
        tvBuyNum.setText((goodsDetail.getResult().getSales()==null?0:goodsDetail.getResult().getSales())+"已购买");
        tvStock.setText("库存\n"+goodsDetail.getResult().getStock());
        tvPostAddress.setText(goodsDetail.getResult().getCommodityMessage().getAddress());
        tvHeat.setText("热度"+goodsDetail.getResult().getHeat());

        StringBuilder sb = new StringBuilder();
        sb.append(getHtmlData(goodsDetail.getResult().getCommodityMessage().getDetailPhoto()));
        tvDetail.loadDataWithBaseURL(null,sb.toString(),"text/html", "utf-8", null);
    }

    /**
     * 富文本适配
     */
    private String getHtmlData(String bodyHTML) {
        String head = "<head>"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
                + "<style>img{max-width: 100%; width:auto; height:auto;}</style>"
                + "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getTitleBarType() {
        return 0;
    }

    /**banner*/
    private void setBanner() {
        String ban []=goodsDetail.getResult().getCommodityMessage().getDetailPhoto().split(",");
        if (ban.length>0){
            banners=new ArrayList<>();
            for (int i=0;i<ban.length;i++){
                banners.add(ban[i]);
            }
        }
        banner.setData(banners,null);
        //加载广告图片
        banner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object object, View view, int position) {
                //在此处使用图片加载框架加载图片，demo中使用glide加载，可替换成自己项目中的图片加载框架
                Glide.with(getApplicationContext()).load(banners.get(position)).
                        placeholder(R.mipmap.icon_goodsdetail_banner)
                        .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
                        .into((ImageView) view);
            }
        });
    }

}
